# -*- coding: utf-8 -*-
from django.shortcuts import HttpResponse,render_to_response,HttpResponseRedirect
from home.forms import *
from django.core.context_processors import csrf
from django.contrib.auth import REDIRECT_FIELD_NAME
from vdir.models import *
from vfile.models import *
from django.core import serializers
import json
from django.db.models import Max

def signin(request):
    context={}
    errorMsg=""
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '/')
    form = SigninForm()
    if request.POST:
        errorMsg="登录失败"
        form = SigninForm(request.POST)
        if form.is_valid():
            #做基本验证外的其他验证
            data=form.cleaned_data
            from django.contrib import auth
            user = auth.authenticate(username=data['username'],\
                password=data['password'])
            if user is not None:
                errorMsg=""
                auth.login(request, user)
                #request.session.delete_test_cookie()
                return HttpResponseRedirect(redirect_to)
            else:
                errorMsg="您输入的用户名或密码不正确，请重试。"
    #request.session.set_test_cookie()
    context['form']=form
    context['errorMsg']=errorMsg
    context.update(csrf(request))
    return render_to_response('home/signin.html',context)

def logout(request, next_page=None):
    next_page = '/';
    from django.contrib import auth
    auth.logout(request)
    return HttpResponseRedirect(next_page or request.path)

def make_info(id=None,recur=False):
    try:
        file_info =[]
        dir_info =[]

        subfiles = None

        if not id:
            subdirs = VDir.objects.filter(parent=None)
        else:
            subdirs = VDir.objects.filter(parent=id)

        if subdirs:
            for dir in subdirs:
                info ={}
                info['version']=dir.ver
                info['name'] = dir.name
                info['path'] = dir.get_full_path()
                info['id']=dir.id
                if recur:
                    (subdir_info,subfile_info)=make_info(id=dir.id,recur=recur)
                    info['dirs']=subdir_info
                    info['files']=subfile_info                

                dir_info.append(info)

        if id:
            subfiles = VFile.objects.filter(dir=id)
            print(subfiles)

        if subfiles:
            for f in subfiles:
                info={}
                info['id']=f.id
                info['version']=f.ver
                info['name'] = f.name
                info['checksum']=f.checksum
                file_info.append(info)
        return (dir_info,file_info)
    except Exception, e:
        print e
        print traceback.format_exc()
        return (dir_info,file_info)

    

def dir(request,id=0):
    data = {}

    try:
        dir=VDir.objects.get(pk=id)
        data['version']=dir.ver
        data['name']=dir.name

        (dir_info,file_info)=make_info(id=id,recur=False)
        data['id'] = id
        data['path']=dir.get_full_path()
        data['dirs']=dir_info
        data['files']=file_info
    except:
        vermax = VDir.objects.all().aggregate(Max('ver'))
        data['version']=vermax['ver__max']
        data['id'] = 0
        data['name']=''
        data['path']='/'
        data['dirs']=make_info()
        data['files']={}
    return HttpResponse(json.dumps(data), content_type="application/json") 

def dirrecur(request,id=0):
    data = {}

    try:
        dir=VDir.objects.get(pk=id)
        data['version']=dir.ver
        data['name']=dir.name
        data['id']=id
        data['path']=dir.get_full_path()
        (dir_info,file_info)=make_info(id=id,recur=True)

        data['dirs']=dir_info
        data['files']=file_info
    except:

        vermax = VDir.objects.all().aggregate(Max('ver'))
        data['version']=vermax['ver__max']
        data['name']=''
        data['path']='/'
        data['id'] = 0
        (dir_info,file_info)=make_info(recur=True)
        data['dirs']=dir_info
        data['files']=file_info
    return HttpResponse(json.dumps(data), content_type="application/json") 
